import { ref, onMounted } from "vue";
import { useRoute, onBeforeRouteUpdate, useRouter } from "vue-router";
import { getTabList, setTabList } from "./cookie";

export function useTabList() {
  const route = useRoute();
  const router = useRouter();

  const tablist = ref([
    {
      title: "首页",
      path: "/",
    },
  ]);

  const initTabsData = () => {
    const tbs = getTabList();
    if (tbs != null && tbs.length > 0) tablist.value = tbs;
  }

  // 在路由变化前进行处理，主要是对选中tab的处理，以及存储tablist
  onBeforeRouteUpdate((to, from) => {
    let title = to.meta.title;
    let path = to.path;
    activeTab.value = path;
    let index = tablist.value.findIndex((item) => item.path == path);
    if (index < 0) {
      tablist.value.push({ title, path });
    }
    setTabList(tablist.value);
  });

  const activeTab = ref(route.path);

  // tab切换处理，主要是路由跳转
  const tabChange = (path) => {
    router.push(path);
  };

  // 删除tab的处理，包括激活状态标签处理, 路由跳转，tablist处理及存储
  const removeTab = (path) => {
    const tabs = tablist.value;
    let activePath = activeTab.value;
    if (activePath === path) {
      tabs.forEach((tab, index) => {
        if (tab.path === path) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activePath = nextTab.path;
          }
        }
      });
    }

    activeTab.value = activePath;
    tablist.value = tabs.filter((tab) => tab.path !== path);
    setTabList(tablist.value);
    router.push(activePath);
  };

  const closeAll = () => {
    onClossTabs('clearAll')
  }

  const closeOthers = () => {
    onClossTabs('clearOthers')
  }

  // 关闭所有标签及关闭其他标签处理，主要是标签激活状态处理、删除对应标签、路由转换、存储tablist
  const onClossTabs = (command) => {
    const tabs = [
      {
        title: "首页",
        path: "/",
      },
    ];
    if (command == "clearAll") {
      activeTab.value = "/";
      router.push("/");
    } else {
      tabs.push(tablist.value.find((item) => item.path == activeTab.value));
    }
    tablist.value = tabs;
    setTabList(tablist.value);
  };

  return {
    activeTab,
    tablist,
    initTabsData,
    tabChange,
    removeTab,
    closeAll,
    closeOthers
  }
}
